package com.cryann.mqttserver.controller;

import com.cryann.mqttserver.mqttProcess.mqttMsgHandler.AbstractMqttHandler;
import com.cryann.mqttserver.mqttProcess.mqttMsgHandler.MqttMsgCheckHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author cRyann
 * @date 2018/12/11 0011 10:21
 * @description:
 */
@RestController("BackController")
@RequestMapping("/test")
@Api("localTest")
public class BackController {

    @Autowired
    private ApplicationContext ctx;

    @ApiOperation(value = "synBean",
            notes = "动态增加Mqtt 消息检查处理器,格式：\n" +
                    "* beanName : com.cryann.mqttserver.mqttProcess.mqttMsgHandler.MQTT_3$1$2_3")
    @RequestMapping(value = "synBean")
    public Object synBean(@RequestParam String beanName, @RequestParam boolean flag) {
        try {
            String simpleName = StringUtils.uncapitalize(StringUtils.substringAfterLast(beanName, "."));

            DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
            Class clazz = Class.forName(beanName);

            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
            defaultListableBeanFactory.registerBeanDefinition(simpleName, beanDefinitionBuilder.getBeanDefinition());
            defaultListableBeanFactory.getSingletonNames();
            //获取动态注册的bean.
            Object obj = ctx.getBean(clazz);
            if ( obj instanceof AbstractMqttHandler ) {
                AbstractMqttHandler mqttHandler = (AbstractMqttHandler) ctx.getBean(clazz);
                MqttMsgCheckHandler.addHandler(mqttHandler, flag);
            }
            return MqttMsgCheckHandler.getMqttHandlers();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
